<template>
  <div class="contract-terms">
    <p style="min-height: 400px" v-html="richTextContent">
    </p>
  </div>
</template>

<script setup>
import { computed, onMounted, ref, watch } from 'vue'
import { ElButton, ElInput, ElOption, ElSelect, ElTable, ElTableColumn, ElMessage } from 'element-plus'
import { Editor } from '@/components/Editor'
import { GetTK } from '@/api/base'
import { debounce } from '@/utils/util'
import { checkFildsStore } from '@/stores/modules/checkFilds'

const props = defineProps({
  Trem: {
    type: Array,
    default: () => []
  },
  Id: {
    type: String,
    default: ''
  },
  title: {
    type: String,
    default: ''
  },
  isBg: {
    type: Boolean,
    default: false
  },
  isShowSubBut: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update:Trem'])

const listTypeInfo = ref([])
const richTextContent = ref('')
const internalTableData = ref([])

const tableData = computed(() => internalTableData.value)

const getTermContent = debounce(async () => {
  try {
    const { Data } = await GetTK({ Code: props.Id, Name: '' })
    listTypeInfo.value = Data
  } catch (error) {

  }
}, 300)

function updateTermContent(termId, term) {
  const selectedTerm = listTypeInfo.value.find(item => item.Id === termId)
  if (selectedTerm) {
    term.TermContent = selectedTerm.Content
    debouncedEmit()
  }
  else {
    debouncedEmit()
  }
}

const checkFild = checkFildsStore()

// 错误校验提示
const validateError = list => {
  list.forEach(val => {
    setTimeout(() => {
      ElMessage.error(`${props.title}是必填项！`)
      checkFild.setData(val)
    }, 100)
  })
}

function addTerm() {
  internalTableData.value.push({ TermID: '', TermContent: '' })
  debouncedEmit()
}

function removeTerm(index) {
  internalTableData.value.splice(index, 1)
  debouncedEmit()
}

const debouncedEmit = debounce(() => {
  emit('update:Trem', internalTableData.value)
}, 500)

function handleRichTextChange(content) {
  richTextContent.value = content
  internalTableData.value =[]
  internalTableData.value.push({ TermID: '', TermContent: content })
  debouncedEmit()
}


const validateTable = () => {
  if (props.isBg) {
    return internalTableData.value.every(term => term.TermID && term.TermContent)
  } else {
    return richTextContent.value.trim() !== ''
  }
}

//监听

watch(() => props.Trem, newValue => {
  // richTextContent.value = ''
  if (props.isBg) {
    internalTableData.value = JSON.parse(JSON.stringify(newValue))
  } else {
    if (newValue.length>0){
      richTextContent.value = newValue.map(term => term.TermContent).join('\n')
    }
  }
  console.log(props.isBg,"q23223")
}, { deep: true, immediate: true })

onMounted(() => {
  getTermContent()
})

defineExpose({ validateTable })
</script>

<style scoped>
.contract-terms {
  max-width: 1000px;
  margin: 0 auto;
}

.mt-4 {
  margin-top: 16px;
}
</style>


